<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="info" icon="el-icon-refresh" @click="handleFilter">
        Refresh
      </el-button>
      <el-button v-if="addBtnRights" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">
        Add
      </el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column label="Group Name">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="Description">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="Create At" width="200" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.create_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Update At" width="200" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          {{ scope.row.update_at }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="Status" width="110" align="center">
        <template slot-scope="scope">
          <el-switch v-if="editBtnRights" :value="scope.row.enabled===1?true:false" active-color="#13ce66" inactive-color="#ff4949" @change="changeStatus($event, scope.row)" />
          <el-switch v-else :value="scope.row.enabled===1?true:false" active-color="#13ce66" inactive-color="#ff4949" disabled="disabled" @change="changeStatus($event, scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="Operation" align="center">
        <template slot-scope="{row}">
          <el-button v-if="editBtnRights" type="primary" icon="el-icon-edit" circle @click="handleEdit(row)" />
          <el-button v-if="delBtnRights" type="danger" icon="el-icon-delete" circle @click="handleDel(row)" />
          <el-button v-if="authBtnRights" type="warning" icon="el-icon-setting" circle @click="handleAuth(row)" />
        </template>
      </el-table-column>
    </el-table>
    <!--pagination-->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getGroupList" />
    <!--edit-form-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="100px" style="width: 450px; margin-left:50px;">
        <el-form-item label="Name" prop="name">
          <el-input v-model="temp.name" placeholder="Name" />
        </el-form-item>
        <el-form-item label="Enabled" prop="enabled">
          <el-switch :value="temp.enabled===1?true:false" active-color="#13ce66" inactive-color="#ff4949" @change="change($event)" />
        </el-form-item>
        <el-form-item label="Description" prop="description">
          <el-input v-model="temp.description" placeholder="Description" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </div>
    </el-dialog>
    <!--edit-auth-->
    <el-dialog title="EditAuth" :visible.sync="authDialogFormVisible">
      <el-tree ref="tree" :data="allRights" show-checkbox node-key="rule_id" :check-strictly="true" :default-checked-keys="authCheckedData" default-expand-all :expand-on-click-node="false">
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span> {{ data.title }} </span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="authDialogFormVisible = false">Cancel</el-button>
        <el-button v-if="saveAuthRights" type="primary" @click="handleSaveAuthData()">Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getGroupList, delGroup, updateGroup, createGroup, updateStatus, haveAuth, saveAuthData } from '@/api/group'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
import { checkBtnAuth } from '@/utils/auth'

export default {
  name: 'GroupList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        status: 'success'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      importanceOptions: [1, 2, 3],
      showReviewer: false,
      temp: {
        group_id: undefined,
        name: '',
        enabled: 1,
        description: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      authDialogFormVisible: false,
      pvData: [],
      downloadLoading: false,
      passwordType: 'password',
      authData: [],
      authCheckedData: [],
      editAuthGroupId: 0,
      addBtnRights: false,
      editBtnRights: false,
      delBtnRights: false,
      authBtnRights: false,
      saveAuthRights: false
    }
  },
  computed: {
    ...mapGetters([
      'allRights'
    ])
  },
  created() {
    this.getGroupList()
  },
  mounted() {
    this.addBtnRights = checkBtnAuth('/group/create')
    this.delBtnRights = checkBtnAuth('/group/del')
    this.editBtnRights = checkBtnAuth('/group/update')
    this.authBtnRights = checkBtnAuth('/group/haveAuth')
    this.saveAuthRights = checkBtnAuth('/auth/saveAuth')
  },
  methods: {
    resetTemp() {
      this.temp = {
        group_id: undefined,
        name: '',
        enabled: 1,
        description: ''
      }
    },
    change(newValue) {
      this.temp.enabled = newValue === true ? 1 : 0
    },
    changeStatus(newValue, row) {
      row.enabled = newValue ? 1 : 0
      updateStatus(row).then(response => {})
    },
    handleAdd() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDel(row) {
      // Delete User
      delGroup(row.group_id).then(response => {
        if (response.code === 100000) {
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
          // this.handleFilter()
        } else {
          this.$message({
            message: 'Failure',
            type: 'error'
          })
        }
      })
    },
    // 编辑
    handleEdit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      updateGroup(this.temp).then(response => {
        if (response.code === 100000) {
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
          this.dialogStatus = ''
          this.dialogFormVisible = false
          // this.handleFilter()
        } else {
          this.$message({
            message: 'Failure',
            type: 'error'
          })
        }
      })
    },
    createData() {
      // Delete User
      createGroup(this.temp).then(response => {
        if (response.code === 100000) {
          this.$notify({
            title: 'Success',
            message: 'Delete Successfully',
            type: 'success',
            duration: 2000
          })
          this.dialogFormVisible = false
        } else {
          this.$message({
            message: 'Failure',
            type: 'error'
          })
        }
      })
    },
    handleSaveAuthData() {
      // Save Auth Data
      const authCheckedData = this.$refs.tree.getCheckedKeys()
      // 使用check-strictly 可以不使用 getHalfCheckedKeys
      // const authParentCheckedData = this.$refs.tree.getHalfCheckedKeys()
      // const allCheckedData = authCheckedData.concat(authParentCheckedData)
      saveAuthData(this.editAuthGroupId, authCheckedData).then(response => {
        const { code, msg } = response
        if (code === 100000) {
          // this.handleFilter()
          this.$notify({
            title: 'Success',
            message: msg,
            type: 'success',
            duration: 2000
          })
          this.authDialogFormVisible = false
        } else {
          this.$message({
            message: 'Failure',
            type: 'error'
          })
        }
      })
    },
    handleAuth(row) {
      this.editAuthGroupId = row.group_id
      haveAuth(row.group_id).then(response => {
        this.authDialogFormVisible = true
        const authData = response.data
        this.$nextTick(function() {
          // console.log(authData)
          this.$refs.tree.setCheckedKeys(authData)
        })
      })
    },
    getGroupList() {
      this.listLoading = true
      getGroupList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.count
        this.listLoading = false
      })
    },
    handleFilter() {
      this.getGroupList()
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 15px
}
.show-pwd {
  position: absolute;
  right: 10px;
  top: 3px;
  font-size: 16px;
  cursor: pointer;
  user-select: none;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
